<template>
  <!-- 照片墙 -->
  <div class="photoWall-wrap">
    <vue-scroll :ops="scrollOption">
      <div class="main publicVCenter">
        <audio class="bgAudio" src="https://static.hudongmiao.com/joymewH5/audio/gbqqNew.mp3" ref="audioDom" loop="loop" preload></audio>
        <img src="@/assets/image/photoWall/bg1.png" class="bg" />
        <img src="@/assets/image/photoWall/barTip.png" class="barTip" />
        <div class="tip">勇敢表达爱，图片会在大屏显示</div>
        <div class="music" :class="{ off: !isMusicPlay, on: isMusicPlay }" v-tap="{ methods: switchMusic }"></div>
        <div class="loves">
          <love
            class="loveItem"
            v-for="item in loveList"
            :key="item.id"
            :activeAni="item.activeAni"
            :imgPath="item.imgPath"
            :choosed="item.isChoosed"
            v-tap="{ methods: chooseLove, locatId: item.id }"
          />
        </div>
        <div class="uploadArea publicVCenter">
          <div class="uploadCamera publicHCenter" v-show="uploadVisible">
            <div class="uploadBtn publicHvCenter" v-show="!fileInputShow">上传照片</div>
            <div class="uploadBtn publicHvCenter" v-show="fileInputShow">{{ heartWallPrice }}元/张</div>
            <input ref="fileinput" accept="image/*" type="file" class="fileInput" @change="change" v-show="fileInputShow" />
            <div class="cArea" v-tap="{ methods: handleFailUpload }" v-show="!fileInputShow"></div>
          </div>
          <div class="exportPhoto publicHvCenter" v-tap="{ methods: generateAlbum }">
            <img src="@/assets/image/photoWall/exportIcon.png" class="exportIcon" />
            查看照片合集
          </div>
        </div>
        <div class="photos publicVCenter">
          <div class="title">图片管理</div>
          <ul>
            <li class="photoItem publicVCenter" v-for="item in photoList" :key="item.id">
              <div class="left publicVCenter">
                <img :src="item.avator" class="headImg" />
                <div class="user">
                  <div class="name">{{ item.wx_name }}</div>
                  <div class="date">{{ item.date }}</div>
                </div>
              </div>
              <div class="right publicVCenter">
                <img :src="item.imgPath" class="loveImg" />
                <img
                  src="@/assets/image/photoWall/deleteIcon.png"
                  class="deleteIcon"
                  v-tap="{ methods: deletePhoto, id: item.id }"
                  v-show="item.userId === userId"
                />
              </div>
            </li>
          </ul>
        </div>
      </div>
    </vue-scroll>
    <cropper
      v-show="tempImg"
      :tempImg="tempImg"
      @cancelCropper="handleCancelCropper"
      @confirmCropper="handleConfirmCropper"
      ref="cropper"
    />
  </div>
</template>
<script>
import { uploadPhoto } from '@/api/index/index';
import { getPhotoWallList, deletePhoto, sendPhoto } from '@/api/photoWall/photoWall';
import {
  timeoutTask, generateRandom, newDateTransform, generateRandomId, getUrlParam,
} from '@/utils/index';
import { sendPhotoWallGiftMessage } from '@/api/chat/index';
import { mapState } from 'vuex';
import cropper from './cropper.vue';
import love from './love.vue';

let endLoop = false;
let tmpResFilePath;
let tmpResFilePathOrigin;
const wx = require('weixin-js-sdk');

export default {
  name: 'photoWallIndex',
  computed: {
    fileInputShow() {
      let tmpFlag = false;
      if (this.loveList.length > 0) {
        const tIndex = this.getChoosedLove();
        if (tIndex > -1) {
          tmpFlag = true;
        }
      }
      return tmpFlag;
    },
    ...mapState({
      userId: (state) => state.user.userId,
      heartWallPrice: (state) => state.app.heartWallPrice,
    }),
  },
  data() {
    return {
      tempImg: '',
      resultImg: '',
      isMusicPlay: false,
      scrollOption: {
        vuescroll: {},
        scrollPanel: {
          scrollingX: false,
          scrollingY: true,
          // 滚动的速度。在你点击滚动轨道或者调用scrollTo或者scrollBy的时候起作用。
          speed: 600,
          // 滚动动画
          easing: 'ease',
        },
        rail: {
          size: '1px',
          background: '#bd38f4',
        },
        bar: {
          background: 'rgba(0,0,0,0.8)',
          keepShow: false,
          onlyShowBarOnScroll: false,
        },
      },
      loveList: [],
      photoList: [],
      defaultHeadImg: require('../../assets/image/defaultHeadImg.png'),
      payStatus: 1,
      uploadVisible: true,
    };
  },
  watch: {
    tempImg(newVal) {
      if (newVal) {
        endLoop = true;
      }
    },
  },
  components: {
    cropper,
    love,
  },
  created() {
    // 处理支付完点击回退不能一次性回到首页的问题
    // const pageLen = window.history.length;
    // if (pageLen > 2) {
    //   window.history.go(2 - pageLen);
    //   window.location.replace(window.location.href);
    // }
    endLoop = false;
    // 是否从分享进入
    const tmpPhotoWallShare = getUrlParam('photoWallShare');
    if (tmpPhotoWallShare) {
      this.uploadVisible = false;
    }
    this.initData(() => {
      if (localStorage.getItem('tmpPhotoWallFilePath')) {
        // 支付成功后的回调
        this.$loading('图片上传中...');
        sendPhoto({
          imgPathOrigin: localStorage.getItem('tmpPhotoWallFilePathOrigin'),
          imgPath: localStorage.getItem('tmpPhotoWallFilePath'),
          id: localStorage.getItem('tmpPhotoWallId'),
        })
          .then((res2) => {
            console.log(res2);
            this.$loading.close();
            const tmpIndex = this.getLoveById(parseInt(localStorage.getItem('tmpPhotoWallId'), 10));
            if (res2.code === '200') {
              this.$toast.center('上传成功!');
              this.initData(() => {
                timeoutTask(() => {
                  sendPhotoWallGiftMessage(localStorage.getItem('tmpPhotoWallFilePathOrigin')).then(() => {
                    localStorage.removeItem('tmpPhotoWallFilePathOrigin');
                  });
                }, 3000);
              });
            } else if (res2.code === '666') {
              this.$toast.center('别人已经买过这个格子啦!重新选择一个吧!');
              this.loveList[tmpIndex].isChoosed = false;
            }
            localStorage.removeItem('tmpPhotoWallFilePath');
            localStorage.removeItem('tmpPhotoWallId');
          })
          .catch((err) => {
            console.log(err);
            this.$loading.close();
            this.$toast.center('上传失败!');
          });
      }
    });
  },
  mounted() {
    wx.config({
      // 配置信息, 即使不正确也能使用 wx.ready
      debug: false,
      appId: '',
      timestamp: 1,
      nonceStr: '',
      signature: '',
      jsApiList: [],
    });
    wx.ready(() => {
      this.isMusicPlay = true;
      this.$refs.audioDom.play();
    });
  },
  methods: {
    initData(cb) {
      this.$loading('数据加载中...');
      getPhotoWallList()
        .then((res) => {
          console.log(res);
          this.$loading.close();
          this.initLoveList(res.list);
          this.initPhotoList(res.list);
          this.loopRunActiveAni(res.list);
          if (cb) {
            cb();
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handleFailUpload() {
      let tmpFlag = true;
      for (let i = 0; i < 21; i += 1) {
        if (!this.loveList[i].imgPath) {
          tmpFlag = false;
          break;
        }
      }
      if (!tmpFlag) {
        this.$toast.center('请在墙上选中一个爱心格子!');
      } else {
        this.$toast.center('爱心格子已经填满啦!欣赏下照片集吧!');
        timeoutTask(() => {
          window.location.href = `/album/album.html?liveId=${this.$store.state.live.liveId}&time=${generateRandomId()}`;
        }, 2000);
      }
    },
    change(e) {
      try {
        this.$loading('图片加载中...');
        const freader = new FileReader();
        const file = e.target.files[0];
        //  const fixOrientation = require('fix-orientation');

        freader.onload = (ev) => {
          const url = ev.target.result;
          this.tempImg = url;
          this.$loading.close();
          // fixOrientation(
          //   freader.result,
          //   {
          //     image: true,
          //   },
          //   (fixedImg) => {
          //     this.tempImg = fixedImg;
          //     this.$loading.close();
          //   },
          // );
        };

        freader.onerror = () => {
          this.$loading.close();
          this.$toast.center('图片加载失败');
        };

        freader.readAsDataURL(file); // 读取照片
      } catch (err) {
        this.$loading.close();
      }
    },
    switchMusic() {
      this.isMusicPlay = !this.isMusicPlay;
      if (this.isMusicPlay) {
        this.$refs.audioDom.play();
      } else {
        this.$refs.audioDom.pause();
      }
    },
    initLoveList(list) {
      this.loveList.splice(0);
      const tmpLen = list.length;
      let tmpIndex = -1;
      for (let i = 0; i < 21; i += 1) {
        for (let j = 0; j < tmpLen; j += 1) {
          if (parseInt(list[j].sort, 10) === i + 1) {
            tmpIndex = j;
            break;
          } else {
            tmpIndex = -1;
          }
        }
        if (tmpIndex > -1) {
          this.loveList.push({
            id: parseInt(list[tmpIndex].sort, 10),
            imgPath: list[tmpIndex].photo_end_url,
            isChoosed: false,
            activeAni: false,
          });
        } else {
          this.loveList.push({
            id: i + 1,
            imgPath: '',
            isChoosed: false,
            activeAni: false,
          });
        }
      }
    },
    initPhotoList(list) {
      this.photoList.splice(0);
      const tmpLen = list.length;
      for (let i = 0; i < tmpLen; i += 1) {
        this.photoList.push({
          id: list[i].heart_wall_id,
          imgPath: list[i].photo_end_url,
          wx_name: list[i].wx_name,
          date: newDateTransform(list[i].create_time),
          userId: list[i].userId,
          avator: list[i].avator,
        });
      }
    },
    deletePhoto(pObj) {
      console.log(pObj.id);
      deletePhoto({ id: pObj.id })
        .then((res) => {
          console.log(res);
          this.initData();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    chooseLove(e) {
      console.log(e.locatId);
      this.resetChoosedLove();
      const tIndex = this.getLoveById(e.locatId);
      if (!this.loveList[tIndex].imgPath) {
        this.loveList[tIndex].isChoosed = true;
      }
    },
    resetChoosedLove() {
      for (let i = 0; i < 21; i += 1) {
        this.loveList[i].isChoosed = false;
      }
    },
    getChoosedLove() {
      let tmpIndex = -1;
      for (let i = 0; i < 21; i += 1) {
        if (this.loveList[i] && this.loveList[i].isChoosed) {
          tmpIndex = i;
          break;
        }
      }
      return tmpIndex;
    },
    getLoveById(pId) {
      let tmpIndex = -1;
      for (let i = 0; i < 21; i += 1) {
        if (this.loveList[i].id === pId) {
          tmpIndex = i;
          break;
        }
      }
      return tmpIndex;
    },
    generateAlbum() {
      let tmpFlag = false;
      for (let i = 0; i < 21; i += 1) {
        if (this.loveList[i].imgPath) {
          tmpFlag = true;
          break;
        }
      }
      if (!tmpFlag) {
        this.$toast.center('至少填满一个爱心格子才能查看照片合集哦!');
      } else {
        window.location.href = `/album/album.html?liveId=${this.$store.state.live.liveId}&time=${generateRandomId()}`;
      }
    },
    handleCancelCropper() {
      this.tempImg = '';
      this.$refs.fileinput.value = '';
      endLoop = false;
      this.loopRunActiveAni();
    },
    handleConfirmCropper(e) {
      this.resultImg = e;

      this.$loading('图片上传中...');
      const tmpIndex = this.getChoosedLove();
      this.uploadOriginPhoto()
        .then((res1) => {
          tmpResFilePathOrigin = res1.filePath;
        })
        .then(() => {
          console.log('***上传照片Origin***');
          return this.uploadPhoto();
        })
        .then((res2) => {
          console.log('***上传照片***');
          console.log(res2);
          tmpResFilePath = res2.filePath;
          return sendPhoto({
            imgPathOrigin: tmpResFilePathOrigin,
            imgPath: tmpResFilePath,
            id: this.loveList[tmpIndex].id,
          });
        })
        .then((res3) => {
          console.log(res3);
          this.$loading.close();
          if (res3.code === '200') {
            this.$toast.center('上传成功!');
            this.loveList[tmpIndex].imgPath = tmpResFilePath;
            this.loveList[tmpIndex].isChoosed = false;
            this.handleCancelCropper();
            sendPhotoWallGiftMessage(tmpResFilePathOrigin);
          } else if (res3.code === '100') {
            // 喵钻不足 跳转支付
            console.log('***跳转地址***');
            localStorage.setItem('tmpPhotoWallId', this.loveList[tmpIndex].id);
            localStorage.setItem('tmpPhotoWallFilePath', tmpResFilePath);
            localStorage.setItem('tmpPhotoWallFilePathOrigin', tmpResFilePathOrigin);
            console.log(
              `/pages/pay/pay?openId=${this.$store.state.user.openId}&userId=${this.$store.state.user.userId}&total=${this.heartWallPrice}`,
            );
            wx.miniProgram.navigateTo({
              url: `/pages/pay/pay?openId=${this.$store.state.user.openId}&userId=${this.$store.state.user.userId}&total=${this.heartWallPrice}`,
            });
          }
        })
        .catch((err) => {
          console.log(err);
          this.$loading.close();
          this.$toast.center('上传失败!');
        });
    },
    uploadPhoto() {
      const formData = new FormData();
      const arr = this.resultImg.split(',');
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      /* eslint-disable */
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      const file = new File([u8arr], 'photo');
      formData.append('file', file);
      formData.append('prefix', 'photoWall');
      return uploadPhoto(formData);
    },
    uploadOriginPhoto() {
      const formData = new FormData();
      const arr = this.tempImg.split(',');
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      /* eslint-disable */
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      const file = new File([u8arr], 'originPhoto');
      formData.append('file', file);
      formData.append('prefix', 'originPhotoWall');
      return uploadPhoto(formData);
    },
    loopRunActiveAni() {
      if (endLoop) {
        return;
      }
      const effectList = this.loveList.filter((item) => {
        return item.imgPath && !item.activeAni;
      });
      const effectLen = effectList.length;
      if (effectLen === 0) {
        return;
      }
      const tIndex = generateRandom(0, effectLen);
      effectList[tIndex].activeAni = true;
      timeoutTask(() => {
        effectList[tIndex].activeAni = false;
      }, 1000);
      timeoutTask(() => {
        this.loopRunActiveAni();
      }, 3000);
    },
  },
  beforeDestroy() {},
};
</script>
<style lang="less" scoped>
img {
  image-rendering: -moz-crisp-edges;
  image-rendering: -o-crisp-edges;

  image-rendering: -webkit-optimize-contrast;
  image-rendering: crisp-edges;
  -ms-interpolation-mode: nearest-neighbor;
}
.photoWall-wrap {
  position: relative;
  width: 100vw;
  height: 100vh;
  background: #0a1f3f;
  .main {
    position: relative;
    width: 100%;
    height: 100%;
    flex-direction: column;
    .bg {
      width: 100%;
      position: absolute;
    }
    .barTip {
      width: 640px;
      height: 144px;
      position: relative;
      margin-top: 63px;
    }
    .tip {
      font-size: 32px;
      font-weight: 500;
      color: #ffffff;
      letter-spacing: 4px;
      position: relative;
      margin-top: 32px;
    }
    .music {
      width: 60px;
      height: 60px;
      background-size: 100% 100%;
      position: absolute;
      top: 250px;
      right: 42px;
      &.off {
        background-image: url('../../assets/image/photoWall/musicIcon.png');
      }
      &.on {
        background-image: url('../../assets/image/photoWall/musicIconActive.png');
        animation-name: rotateAni;
        animation-duration: 2s;
        animation-timing-function: linear;
        animation-iteration-count: infinite;
      }
    }
    .loves {
      width: 100%;
      height: 702px;
      position: relative;
      margin-top: 90px;
      .loveItem {
        position: absolute;
        &:nth-child(1) {
          width: 17.6vw;
          height: 17.6vw;
          left: 15.733vw;
          top: -2vw;
        }
        &:nth-child(2) {
          width: 17.6vw;
          height: 17.6vw;
          right: 15.733vw;
          top: -2vw;
        }
        &:nth-child(3) {
          width: 17.6vw;
          height: 17.6vw;
          left: 2.133vw;
          top: 8.8vw;
        }
        &:nth-child(4) {
          width: 17.6vw;
          height: 17.6vw;
          left: 29.267vw;
          top: 9.333vw;
        }
        &:nth-child(5) {
          width: 17.6vw;
          height: 17.6vw;
          right: 29.267vw;
          top: 9.333vw;
        }
        &:nth-child(6) {
          width: 17.6vw;
          height: 17.6vw;
          right: 2.133vw;
          top: 8.8vw;
        }
        &:nth-child(7) {
          width: 17.6vw;
          height: 17.6vw;
          left: -2.667vw;
          top: 25.333vw;
        }
        &:nth-child(8) {
          width: 20.267vw;
          height: 20.267vw;
          left: 14.4vw;
          top: 20vw;
        }
        &:nth-child(9) {
          width: 24.533vw;
          height: 24.533vw;
          left: 37.867vw;
          top: 23vw;
        }
        &:nth-child(10) {
          width: 20.267vw;
          height: 20.267vw;
          right: 14.4vw;
          top: 20vw;
        }
        &:nth-child(11) {
          width: 17.6vw;
          height: 17.6vw;
          right: -2.667vw;
          top: 25.333vw;
        }

        &:nth-child(12) {
          width: 17.6vw;
          height: 17.6vw;
          left: 2.667vw;
          top: 41.667vw;
        }
        &:nth-child(13) {
          width: 20.267vw;
          height: 20.267vw;
          left: 24.667vw;
          top: 39.333vw;
        }
        &:nth-child(14) {
          width: 20.267vw;
          height: 20.267vw;
          right: 24.667vw;
          top: 39.333vw;
        }
        &:nth-child(15) {
          width: 17.6vw;
          height: 17.6vw;
          right: 2.667vw;
          top: 41.667vw;
        }

        &:nth-child(16) {
          width: 17.6vw;
          height: 17.6vw;
          left: 14.4vw;
          top: 55vw;
        }
        &:nth-child(17) {
          width: 29.333vw;
          height: 29.333vw;
          left: 35.467vw;
          top: 53.333vw;
        }
        &:nth-child(18) {
          width: 17.6vw;
          height: 17.6vw;
          right: 14.4vw;
          top: 55vw;
        }
        &:nth-child(19) {
          width: 17.6vw;
          height: 17.6vw;
          left: 24.267vw;
          top: 72vw;
        }
        &:nth-child(20) {
          width: 17.6vw;
          height: 17.6vw;
          right: 24.267vw;
          top: 72vw;
        }
        &:nth-child(21) {
          width: 20.267vw;
          height: 20.267vw;
          left: 39.733vw;
          top: 80.667vw;
        }
        &.choosed {
          border: 1px solid red;
        }
      }
    }
    .uploadArea {
      width: 100%;
      height: 560px;
      background-image: url('../../assets/image/photoWall/bg2.png');
      background-size: 100% 100%;
      position: relative;
      flex-direction: column;
      padding-top: 92px;
      .uploadCamera {
        margin-top: 28px;
        width: 196px;
        height: 190px;
        background-image: url('../../assets/image/photoWall/cameraIcon.png');
        background-size: 100% 100%;
        position: relative;
        .uploadBtn {
          width: 188px;
          height: 48px;
          background: linear-gradient(90deg,#6c47ff, #ff68f9 100%);
          box-shadow: 0px 4px 12px -4px #b59336;
          border-radius: 24px;
          position: absolute;
          font-size: 28px;
          font-weight: 500;
          color: #fff;
          top: 144px;
        }
        .fileInput {
          position: absolute;
          width: 152%;
          height: 111%;
          opacity: 0;
        }
        .cArea {
          position: absolute;
          width: 152%;
          height: 111%;
          opacity: 0;
        }
      }
      .exportPhoto {
        width: 220px;
        height: 56px;
        background: rgba(255, 201, 146, 0.14);
        border-radius: 34px;
        font-size: 24px;
        font-weight: 400;
        color: #ffffff;
        margin-top: 54px;
        .exportIcon {
          width: 24px;
          height: 30px;
          margin-right: 14px;
        }
      }
    }
    .photos {
      position: relative;
      width: 100%;
      padding-top: 60px;
      padding-bottom: 100px;
      flex-direction: column;
      background: #0a1f3f;
      .title {
        font-size: 36px;
        font-weight: 500;
        color: #ffffff;
        position: relative;
        &::before {
          content: '';
          position: absolute;
          left: -100px;
          top: 24px;
          width: 100px;
          height: 4px;
          background-color: #ffffff;
        }
        &::after {
          content: '';
          position: absolute;
          right: -100px;
          top: 24px;
          width: 100px;
          height: 4px;
          background-color: #ffffff;
        }
      }
      ul {
        margin-top: 62px;
        width: 100%;
        .photoItem {
          height: 78px;
          justify-content: space-between;
          width: 100%;
          list-style: none;
          margin-bottom: 64px;
          .left {
            height: 100%;
            padding-left: 32px;
            .headImg {
              width: 80px;
              height: 80px;
              border-radius: 50%;
            }
            .user {
              margin-left: 24px;
              .name {
                font-size: 30px;
                font-weight: 500;
                color: #ffffff;
                max-width: 44vw;
                text-overflow: ellipsis;
                white-space: nowrap;
                overflow: hidden;
              }
              .date {
                font-size: 22px;
                font-weight: 300;
                color: #ffffff;
                margin-top: 4px;
              }
            }
          }
          .right {
            height: 100%;
            padding-right: 40px;
            width: 28vw;
            .loveImg {
              width: 92px;
              height: 80px;
              margin-right: 40px;
            }
            .deleteIcon {
              width: 36px;
              height: 36px;
            }
          }
        }
      }
    }
    @keyframes rotateAni {
      0% {
        transform: rotate(0deg);
      }
      50% {
        transform: rotate(-180deg);
      }
      100% {
        transform: rotate(-360deg);
      }
    }
  }
}
</style>
